package com.shu.Thread;

import com.google.common.base.Stopwatch;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPool {


    @Test
    public void name() throws InterruptedException {
        Stopwatch stopwatch = Stopwatch.createStarted();

        // 1,1,0
        Executors.newSingleThreadExecutor().submit(() -> {
            System.out.println("" + Thread.currentThread().getName());
        });

        // n,n,0
        Executors.newFixedThreadPool(2).submit(() -> {
            System.out.println("" + Thread.currentThread().getName());
        });

        // 0,max,60
        Executors.newCachedThreadPool().submit(() -> {
            System.out.println("" + Thread.currentThread().getName());
        });

        // n,max,0
        Executors.newScheduledThreadPool(2).schedule(() -> {
            System.out.println("" + Thread.currentThread().getName());
            System.out.println(stopwatch.elapsed(TimeUnit.SECONDS) + "秒后执行");
        }, 1L, TimeUnit.SECONDS);

        Executors.newWorkStealingPool().submit(() -> {
            System.out.println("" + Thread.currentThread().getName());
        });

        Thread.sleep(10000);
    }


    @Test
    public void test2() throws IOException {

        int corePoolSize = 2;
        int maximumPoolSize = 4;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(6);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

        for (int i = 0; i < 10; i++) {
            Thread th = new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println("i am in" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("i am out" + Thread.currentThread().getName());
                }
            });

            executor.execute(th);
        }
        System.in.read();
    }



}
